import cryptico from 'cryptico';

class RSA {
  constructor() {
    this.keyCache = {};
    this.bits = 1024;

    this.getKeys('local');
  }

  getKeys(type) {
    if (!this.keyCache[type]) {
      this.keyCache[type] = this.generateKeys();
    }
    return this.keyCache[type] || {};
  }

  generateKeys() {
    let privateKey = cryptico.generateRSAKey(Date.now().toString(), this.bits);
    let publicKey = cryptico.publicKeyString(privateKey);
    return {
      public: publicKey,
      private: privateKey
    };
  }

  decrypt(ciphertext, privateKey) {
    if (!privateKey) {
      return null;
    }
    let decrypted = cryptico.decrypt(ciphertext, privateKey);
    if (decrypted && decrypted.status === 'success') {
      return decrypted.plaintext;
    }
    return null;
  }

  encrypt(plaintext, publicKey) {
    if (!publicKey) {
      return null;
    }
    let encrypted = cryptico.encrypt(plaintext, publicKey);
    if (encrypted && encrypted.status === 'success') {
      return encrypted.cipher;
    }
    return null;
  }
}

export default new RSA();
